﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Framework.Library.Core.Config;
using System.IO;
using System.Web;
using System.Drawing;
using Framework.Library.Core.Utils.Text;

namespace Framework.Library.Core.Utils.GlobalHelper
{
    public class FileHelper
    {
        public static Configurations cfg
        {
            get { return new Configurations(); }
        }

        public static string view_tree(string uploadPath)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<ul class=\"treeview\"><li class=\"selected\"><a class=\"root\" href=\"" + uploadPath + "\">" + Path.GetFileName(uploadPath.Trim('/')) + "</a>");
            //sb.Append("<ul class=\"treeview\">");
            sb.Append(HtmlHelper.RenderTree(uploadPath));
            sb.Append("</li></ul>");
            //sb.Append("</ul>");
            return sb.ToString();
        }

        public static byte[] view_thumb(string file, int h, int w, out string contentType)
        {
            HttpContext context = HttpContext.Current;
            try
            {                
                MemoryStream imageStream = new MemoryStream();
                using (System.Drawing.Image image = System.Drawing.Image.FromFile(context.Server.MapPath(file)))
                {
                    if (h == 0)
                        h = image.Height;
                    if (w == 0)
                        w = image.Width;
                    int normalWidth = image.Width;
                    int normalHeight = image.Height;
                    double percent = 1;
                    if (normalHeight > normalWidth)
                    {
                        if (normalHeight > h)
                        {
                            percent = (double)normalWidth / normalHeight;
                            w = (int)(w * percent);
                        }
                        else
                        {
                            h = normalHeight;
                            w = normalWidth;
                        }

                    }
                    else
                    {
                        if (normalWidth > w)
                        {
                            percent = (double)normalHeight / normalWidth;
                            h = (int)(h * percent);
                        }
                        else
                        {
                            h = normalHeight;
                            w = normalWidth;
                        }
                    }
                    System.Drawing.Image thumbnailImage = image.GetThumbnailImage(w, h, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
                    thumbnailImage.Save(imageStream, StaticData.ImageFormatDictionary[Path.GetExtension(context.Server.MapPath(file))]);
                    byte[] imageContent = new Byte[imageStream.Length];
                    imageStream.Position = 0;
                    imageStream.Read(imageContent, 0, (int)imageStream.Length);

                    image.Dispose();
                    contentType = StaticData.MIMETypesDictionary[Path.GetExtension(context.Server.MapPath(file))];
                    return imageContent;
                }
            }
            catch (Exception ex)
            {
                file = "/Resource/Images/filemanager/256/png.png";
                MemoryStream imageStream = new MemoryStream();
                System.Drawing.Image image = System.Drawing.Image.FromFile(context.Server.MapPath(file));
                int normalWidth = image.Width;
                int normalHeight = image.Height;
                if (normalHeight > normalWidth)
                {
                    if (normalHeight > h)
                    {
                        double percent = (double)normalWidth / normalHeight;
                        w = (int)(w * percent);
                    }
                }
                else
                {
                    if (normalWidth > w)
                    {
                        double percent = (double)normalHeight / normalWidth;
                        h = (int)(h * percent);
                    }
                }
                System.Drawing.Image thumbnailImage = image.GetThumbnailImage(w, h, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);

                thumbnailImage.Save(imageStream, StaticData.ImageFormatDictionary[Path.GetExtension(context.Server.MapPath(file))]);
                byte[] imageContent = new Byte[imageStream.Length];
                imageStream.Position = 0;
                imageStream.Read(imageContent, 0, (int)imageStream.Length);
                contentType = StaticData.MIMETypesDictionary[Path.GetExtension(context.Server.MapPath(file))];
                return imageContent;
            }
        }
        private static bool ThumbnailCallback()
        {
            return true;
        }

        public static string view_spec(string pathFile, string type)
        {
            HttpContext context = HttpContext.Current;
            StringBuilder sb = new StringBuilder();
            string serverPath = context.Server.MapPath(pathFile);
            switch (type)
            {
                case "image":
                    using (Image img = Image.FromFile(serverPath))
                    {
                        FileInfo infoImage = new FileInfo(serverPath);
                        sb.AppendFormat("<div class=\"icon image\"><img src=\"/Resources.ashx?module=popup&action=view_thumb&h=140&amp;w=140&amp;far=1&amp;src={0}&bg=0000FF\" alt=\"{1}\" /></div>", HttpUtility.UrlEncode(pathFile), Path.GetFileName(serverPath));
                        sb.AppendFormat("<div class=\"filename\"><a href=\"{0}\" rel=\"lightbox\">{1}</a></div>", pathFile, Path.GetFileName(serverPath));
                        sb.Append("<div class=\"filetype\">" + StaticData.MIMETypesDictionary[Path.GetExtension(serverPath)] + "</div>");
                        sb.AppendFormat("<div class=\"filemodified\"><span>Modified on:&nbsp;</span>{0}</div>", infoImage.LastAccessTime.ToString("dd/MM/yyyy HH:mm:ss"));
                        sb.AppendFormat("<div class=\"filesize\"><span>Size:&nbsp;</span>{0}</div>", FormatUtils.FileSizeToString(infoImage.Length));
                        sb.AppendFormat("<div class=\"filedim\"><span>Dimensions:&nbsp;</span>{0} x {1}</div>", img.Width, img.Height);
                        img.Dispose();
                    }
                    break;
                case "file":
                    FileInfo infoFile = new FileInfo(serverPath);
                    sb.Append("<div class=\"icon " + Path.GetExtension(serverPath).Trim('.') + "\"></div>");
                    sb.Append("<div class=\"filename\">" + Path.GetFileName(serverPath) + "</div>");
                    sb.Append("<div class=\"filetype\">" + StaticData.MIMETypesDictionary[Path.GetExtension(serverPath)] + "</div>");
                    sb.AppendFormat("<div class=\"filemodified\"><span>Modified on:&nbsp;</span>{0}</div>", infoFile.LastAccessTime.ToString("dd/MM/yyyy HH:mm:ss"));
                    sb.AppendFormat("<div class=\"filesize\"><span>Size:&nbsp;</span>{0}</div>", FormatUtils.FileSizeToString(infoFile.Length));
                    break;
                default:
                    FileInfo infoDir = new FileInfo(serverPath);
                    sb.Append("<div class=\"icon folder\"></div>");
                    sb.AppendFormat("<div class=\"filename\">{0}</div>", infoDir.Directory.Name);
                    sb.Append("<div class=\"filetype\">Directory</div>");
                    sb.AppendFormat("<div class=\"filemodified\"><span>Modified on:&nbsp;</span>{0}</div>", infoDir.LastAccessTime.ToString("dd/MM/yyyy HH:mm:ss"));
                    break;
            }
            return sb.ToString();
        }

        public static string view_data(LayoutView layout, string path)
        {
            HttpContext context = HttpContext.Current;
            StringBuilder sb = new StringBuilder();           
            switch (layout)
            {
                case LayoutView.content:
                    sb.Append(view_content(path));
                    break;
                case LayoutView.details:
                    sb.Append(view_details(path));
                    break;
                case LayoutView.large_images:
                    sb.Append(view_large_images(path));
                    break;
                case LayoutView.list:
                    sb.Append(view_list(path));
                    break;
                case LayoutView.small_images:
                    sb.Append(view_small_images(path));
                    break;
                case LayoutView.tiles:
                    sb.Append(view_tiles(path));
                    break;
            }
            return sb.ToString();
        }
        public static string view_content(string dir)
        {
            HttpContext context = HttpContext.Current;
            StringBuilder sb = new StringBuilder();
            sb.Append("<ul id=\"content\" class=\"files\">\n");
            string[] arrDir = Directory.GetDirectories(context.Server.MapPath(dir));
            if (arrDir.Length > 0)
            {
                foreach (string strDir in arrDir)
                {
                    string perDir = Path.GetFileName(strDir);
                    sb.Append("<li>");
                    sb.AppendFormat("<a href=\"{0}\" title=\"{1}\" class=\"folder\">", dir + perDir + "/", perDir);
                    sb.Append("<span class=\"begin\"></span>");
                    sb.AppendFormat("<span class=\"filename\">{0}</span>", perDir);
                    sb.Append("<span class=\"icon folder\"></span>");
                    sb.Append("</a>");
                    sb.Append("</li>\n");
                }
            }
            FileInfo[] arrFile = new DirectoryInfo(context.Server.MapPath(dir)).GetFiles();
            if (arrFile.Length > 0)
            {
                foreach (FileInfo strFile in arrFile)
                {
                    string fileSize = FormatUtils.FileSizeToString(strFile.Length);
                    string extFile = string.Empty;
                    if (StaticData.MIMETypesDictionary.ContainsKey(strFile.Extension.ToLower()))
                        extFile = StaticData.MIMETypesDictionary[strFile.Extension.ToLower()];
                    if (strFile.Extension.ToLower() == ".png" || strFile.Extension.ToLower() == ".jpg" || strFile.Extension.ToLower() == ".jpeg" || strFile.Extension.ToLower() == ".gif" || strFile.Extension.ToLower() == ".bmp" || strFile.Extension.ToLower() == ".ico")
                    {
                        using (Image img = Image.FromFile(strFile.FullName))
                        {
                            sb.Append("<li>");
                            sb.Append("<a href=\"" + dir + strFile.Name + "\" title=\"" + strFile.Name + "\" class=\"image\">");
                            sb.Append("<span class=\"begin\"></span>");
                            sb.Append("<span class=\"filename\">" + strFile.Name + "</span>");
                            sb.Append("<span class=\"filetype\"><span class=\"label\">Filetype:</span> " + extFile + "</span>");
                            sb.Append("<span class=\"filedim\"><span class=\"label\">Dimensions</span> " + img.Width + " x " + img.Height + "</span>");
                            sb.Append("<span class=\"filemodified\"><span class=\"label\">Modified on:</span> " + strFile.LastAccessTime.ToString("dd/MM/yyyy HH:mm:ss") + "</span>");
                            sb.Append("<span class=\"filesize\"><span class=\"label\">Size:</span> " + fileSize + "</span>");
                            sb.Append("<span class=\"icon image\"><img src=\"/Resources.ashx?module=popup&action=view_thumb&h=32&w=32&src=" + HttpUtility.UrlEncode(dir + strFile.Name) + "&far=1&bg=0000FF\" /></span>");
                            sb.Append("</a>");
                            sb.Append("</li>\n");
                            img.Dispose();
                        }
                    }
                    else
                    {
                        sb.Append("<li>");
                        sb.Append("<a href=\"" + dir + strFile.Name + "\" title=\"" + strFile.Name + "\" class=\"file\">");
                        sb.Append("<span class=\"begin\"></span>");
                        sb.Append("<span class=\"filename\">" + strFile.Name + "</span>");
                        sb.Append("<span class=\"filetype\"><span class=\"label\">Filetype:</span> " + extFile + "</span>");
                        sb.Append("<span class=\"filemodified\"><span class=\"label\">Modified on:</span> " + strFile.LastAccessTime.ToString("dd/MM/yyyy HH:mm:ss") + "</span>");
                        sb.Append("<span class=\"filesize\"><span class=\"label\">Size:</span> " + fileSize + "</span>");
                        sb.Append("<span class=\"icon " + strFile.Extension.Trim('.') + "\"></span>");
                        sb.Append("</a>");
                        sb.Append("</li>\n");
                    }
                }
            }
            sb.Append("</ul>\n");
            return sb.ToString();
        }
        public static string view_details(string dir)
        {
            HttpContext context = HttpContext.Current;
            StringBuilder sb = new StringBuilder();
            sb.Append("<table id=\"details\" class=\"files\">");
            sb.Append("<thead>");
            sb.Append("<tr>");
            sb.Append("<th colspan=\"3\" class=\"filename\">Filename</th>");
            sb.Append("<th>Modified on</th>");
            sb.Append("<th>Filetype</th>");
            sb.Append("<th>Size</th>");
            sb.Append("<th>Dimensions</th>");
            sb.Append("<th class=\"end\">&nbsp;</th>");
            sb.Append("</tr>");
            sb.Append("</thead>");
            sb.Append("<tbody>");
            string[] arrDir = Directory.GetDirectories(context.Server.MapPath(dir));
            if (arrDir.Length > 0)
            {
                foreach (string strDir in arrDir)
                {
                    string perDir = Path.GetFileName(strDir);
                    FileInfo infoDir = new FileInfo(strDir);
                    sb.AppendFormat("<tr href=\"{0}\" class=\"folder\">", dir + perDir + "/");
                    sb.Append("<td class=\"begin\"></td>");
                    sb.Append("<td class=\"icon\"><span class=\"folder\"></span></td>");
                    sb.AppendFormat("<td class=\"filename\">{0}</td>", perDir);
                    sb.AppendFormat("<td class=\"filemodified\">{0}</td>", infoDir.LastAccessTime.ToString("dd/MM/yyyy HH:mm:ss"));
                    sb.Append("<td class=\"filetype\">Directory</td>");
                    sb.Append("<td class=\"filesize\">&nbsp;</td>");
                    sb.Append("<td class=\"filedim\">&nbsp;</td>");
                    sb.Append("<td class=\"end\">&nbsp;</td>");
                    sb.Append("</tr>");
                }
            }
            FileInfo[] arrFile = new DirectoryInfo(context.Server.MapPath(dir)).GetFiles();
            if (arrFile.Length > 0)
            {
                foreach (FileInfo strFile in arrFile)
                {
                    string fileSize = FormatUtils.FileSizeToString(strFile.Length);
                    if (strFile.Extension.ToLower() == ".png" || strFile.Extension.ToLower() == ".jpg" || strFile.Extension.ToLower() == ".jpeg" || strFile.Extension.ToLower() == ".gif" || strFile.Extension.ToLower() == ".bmp")
                    {
                        using (Image img = Image.FromFile(strFile.FullName))
                        {
                            sb.Append("<tr href=\"" + dir + strFile.Name + "\" class=\"image\">");
                            sb.Append("<td class=\"begin\"></td>");
                            sb.Append("<td class=\"icon\"><span class=\"" + strFile.Extension.Trim('.') + "\"></span></td>");
                            sb.Append("<td class=\"filename\">" + strFile.Name + "</td>");
                            sb.Append("<td class=\"filemodified\">" + strFile.LastAccessTime.ToString("dd/MM/yyyy HH:mm:ss") + "</td>");
                            sb.Append("<td class=\"filetype\">" + StaticData.MIMETypesDictionary[strFile.Extension.ToLower()] + "</td>");
                            sb.Append("<td class=\"filesize\">" + fileSize + "</td>");
                            sb.Append("<td class=\"filedim\">" + img.Width + " x " + img.Height + "</td>");
                            sb.Append("<td class=\"end\">&nbsp;</td>");
                            sb.Append("</tr>");
                            img.Dispose();
                        }
                    }
                    else
                    {
                        sb.Append("<tr href=\"" + dir + strFile.Name + "\" class=\"file\">");
                        sb.Append("<td class=\"begin\"></td>");
                        sb.Append("<td class=\"icon\"><span class=\"" + strFile.Extension.Trim('.') + "\"></span></td>");
                        sb.Append("<td class=\"filename\">" + strFile.Name + "</td>");
                        sb.Append("<td class=\"filemodified\">" + strFile.LastAccessTime.ToString("dd/MM/yyyy HH:mm:ss") + "</td>");
                        sb.Append("<td class=\"filetype\">" + StaticData.MIMETypesDictionary[strFile.Extension.ToLower()] + "</td>");
                        sb.Append("<td class=\"filesize\">" + fileSize + "</td>");
                        sb.Append("<td class=\"filedim\">&nbsp;</td>");
                        sb.Append("<td class=\"end\">&nbsp;</td>");
                        sb.Append("</tr>\n");
                    }
                }
            }
            sb.Append("</tbody>");
            sb.Append("</table>");
            return sb.ToString();
        }
        public static string view_large_images(string dir)
        {
            HttpContext context = HttpContext.Current;
            StringBuilder sb = new StringBuilder();
            sb.Append("<ul id=\"large_images\" class=\"files clear\">\n");
            string[] arrDir = Directory.GetDirectories(context.Server.MapPath(dir));
            if (arrDir.Length > 0)
            {
                foreach (string strDir in arrDir)
                {
                    string perDir = Path.GetFileName(strDir);
                    sb.Append("<li>");
                    sb.AppendFormat("<a href=\"{0}\" title=\"{1}\" class=\"folder\">", dir + perDir + "/", perDir);
                    sb.Append("<span class=\"begin\"></span>");
                    sb.AppendFormat("<span class=\"filename\">{0}</span>", perDir);
                    sb.Append("<span class=\"icon folder\"></span>");
                    sb.Append("</a>");
                    sb.Append("</li>\n");
                }
            }
            FileInfo[] arrFile = new DirectoryInfo(context.Server.MapPath(dir)).GetFiles();
            if (arrFile.Length > 0)
            {
                foreach (FileInfo strFile in arrFile)
                {
                    string fileSize = FormatUtils.FileSizeToString(strFile.Length);
                    if (strFile.Extension.ToLower() == ".png" || strFile.Extension.ToLower() == ".jpg" || strFile.Extension.ToLower() == ".jpeg" || strFile.Extension.ToLower() == ".gif" || strFile.Extension.ToLower() == ".bmp")
                    {
                        using (Image img = Image.FromFile(strFile.FullName))
                        {
                            sb.Append("<li>");
                            sb.Append("<a href=\"" + dir + strFile.Name + "\" title=\"" + strFile.Name + "\" class=\"image\">");
                            sb.Append("<span class=\"begin\"></span>");
                            sb.Append("<span class=\"filename\">" + strFile.Name + "</span>");
                            sb.Append("<span class=\"icon image\"><img src=\"/Resources.ashx?module=popup&action=view_thumb&h=97&w=97&src=" + HttpUtility.UrlEncode(dir + strFile.Name) + "&far=1&bg=0000FF\" /></span>");
                            sb.Append("</a>");
                            sb.Append("</li>\n");
                            img.Dispose();
                        }
                    }
                    else
                    {
                        sb.Append("<li>");
                        sb.Append("<a href=\"" + dir + strFile.Name + "\" title=\"" + strFile.Name + "\" class=\"file\">");
                        sb.Append("<span class=\"begin\"></span>");
                        sb.Append("<span class=\"filename\">" + strFile.Name + "</span>");
                        sb.Append("<span class=\"icon " + strFile.Extension.Trim('.') + "\"></span>");
                        sb.Append("</a>");
                        sb.Append("</li>\n");
                    }
                }
            }
            sb.Append("</ul>\n");
            return sb.ToString();
        }
        public static string view_list(string dir)
        {
            HttpContext context = HttpContext.Current;
            StringBuilder sb = new StringBuilder();
            sb.Append("<ul id=\"list\" class=\"files\">\n");
            string[] arrDir = Directory.GetDirectories(context.Server.MapPath(dir));
            if (arrDir.Length > 0)
            {
                foreach (string strDir in arrDir)
                {
                    string perDir = Path.GetFileName(strDir);
                    sb.Append("<li>");
                    sb.AppendFormat("<a href=\"{0}\" title=\"{1}\" class=\"folder\">", dir + perDir + "/", perDir);
                    sb.Append("<span class=\"begin\"></span>");
                    sb.AppendFormat("<span class=\"filename\">{0}</span>", perDir);
                    sb.Append("<span class=\"icon folder\"></span>");
                    sb.Append("</a>");
                    sb.Append("</li>\n");
                }
            }
            FileInfo[] arrFile = new DirectoryInfo(context.Server.MapPath(dir)).GetFiles();
            if (arrFile.Length > 0)
            {
                foreach (FileInfo strFile in arrFile)
                {
                    string fileSize = FormatUtils.FileSizeToString(strFile.Length);
                    if (strFile.Extension.ToLower() == ".png" || strFile.Extension.ToLower() == ".jpg" || strFile.Extension.ToLower() == ".jpeg" || strFile.Extension.ToLower() == ".gif" || strFile.Extension.ToLower() == ".bmp")
                    {
                        using (Image img = Image.FromFile(strFile.FullName))
                        {
                            sb.Append("<li>");
                            sb.Append("<a href=\"" + dir + strFile.Name + "\" title=\"" + strFile.Name + "\" class=\"image\">");
                            sb.Append("<span class=\"begin\"></span>");
                            sb.Append("<span class=\"filename\">" + strFile.Name + "</span>");
                            sb.Append("<span class=\"icon " + strFile.Extension.Trim('.') + "\"></span>");
                            sb.Append("</a>");
                            sb.Append("</li>\n");
                            img.Dispose();
                        }
                    }
                    else
                    {
                        sb.Append("<li>");
                        sb.Append("<a href=\"" + dir + strFile.Name + "\" title=\"" + strFile.Name + "\" class=\"file\">");
                        sb.Append("<span class=\"begin\"></span>");
                        sb.Append("<span class=\"filename\">" + strFile.Name + "</span>");
                        sb.Append("<span class=\"icon " + strFile.Extension.Trim('.') + "\"></span>");
                        sb.Append("</a>");
                        sb.Append("</li>\n");
                    }
                }
            }
            sb.Append("</ul>\n");
            return sb.ToString();
        }
        public static string view_small_images(string dir)
        {
            HttpContext context = HttpContext.Current;
            StringBuilder sb = new StringBuilder();
            sb.Append("<ul id=\"small_images\" class=\"files clear\">\n");
            string[] arrDir = Directory.GetDirectories(context.Server.MapPath(dir));
            if (arrDir.Length > 0)
            {
                foreach (string strDir in arrDir)
                {
                    string perDir = Path.GetFileName(strDir);
                    sb.Append("<li>");
                    sb.AppendFormat("<a href=\"{0}\" title=\"{1}\" class=\"folder\">", dir + perDir + "/", perDir);
                    sb.Append("<span class=\"begin\"></span>");
                    sb.AppendFormat("<span class=\"filename\">{0}</span>", perDir);
                    sb.Append("<span class=\"icon folder\"></span>");
                    sb.Append("</a>");
                    sb.Append("</li>\n");
                }
            }
            FileInfo[] arrFile = new DirectoryInfo(context.Server.MapPath(dir)).GetFiles();
            if (arrFile.Length > 0)
            {
                foreach (FileInfo strFile in arrFile)
                {
                    string fileSize = FormatUtils.FileSizeToString(strFile.Length);
                    if (strFile.Extension.ToLower() == ".png" || strFile.Extension.ToLower() == ".jpg" || strFile.Extension.ToLower() == ".jpeg" || strFile.Extension.ToLower() == ".gif" || strFile.Extension.ToLower() == ".bmp" || strFile.Extension.ToLower() == ".ico")
                    {
                        using (Image img = Image.FromFile(strFile.FullName))
                        {
                            sb.Append("<li>");
                            sb.Append("<a href=\"" + dir + strFile.Name + "\" title=\"" + strFile.Name + "\" class=\"image\">");
                            sb.Append("<span class=\"begin\"></span>");
                            sb.Append("<span class=\"filename\">" + strFile.Name + "</span>");
                            sb.Append("<span class=\"icon image\"><img src=\"/Resources.ashx?module=popup&action=view_thumb&h=48&w=48&src=" + HttpUtility.UrlEncode(dir + strFile.Name) + "&far=1&bg=0000FF\" /></span>");
                            sb.Append("</a>");
                            sb.Append("</li>\n");
                            img.Dispose();
                        }
                    }
                    else
                    {
                        sb.Append("<li>");
                        sb.Append("<a href=\"" + dir + strFile.Name + "\" title=\"" + strFile.Name + "\" class=\"file\">");
                        sb.Append("<span class=\"begin\"></span>");
                        sb.Append("<span class=\"filename\">" + strFile.Name + "</span>");
                        sb.Append("<span class=\"icon " + strFile.Extension.Trim('.') + "\"></span>");
                        sb.Append("</a>");
                        sb.Append("</li>\n");
                    }
                }
            }
            sb.Append("</ul>\n");
            return sb.ToString();
        }
        public static string view_tiles(string dir)
        {
            HttpContext context = HttpContext.Current;
            StringBuilder sb = new StringBuilder();
            sb.Append("<ul id=\"tiles\" class=\"files clear\">\n");
            string[] arrDir = Directory.GetDirectories(context.Server.MapPath(dir));
            if (arrDir.Length > 0)
            {
                foreach (string strDir in arrDir)
                {
                    string perDir = Path.GetFileName(strDir);
                    sb.Append("<li>");
                    sb.AppendFormat("<a href=\"{0}\" title=\"{1}\" class=\"folder\">", dir + perDir + "/", perDir);
                    sb.Append("<span class=\"begin\"></span>");
                    sb.AppendFormat("<span class=\"filename\">{0}</span>", perDir);
                    sb.AppendFormat("<span class=\"filetype\">Directory</span>");
                    sb.Append("<span class=\"icon folder\"></span>");
                    sb.Append("</a>");
                    sb.Append("</li>\n");
                }
            }
            FileInfo[] arrFile = new DirectoryInfo(context.Server.MapPath(dir)).GetFiles();
            if (arrFile.Length > 0)
            {
                foreach (FileInfo strFile in arrFile)
                {
                    string fileSize = FormatUtils.FileSizeToString(strFile.Length);
                    if (strFile.Extension.ToLower() == ".png" || strFile.Extension.ToLower() == ".jpg" || strFile.Extension.ToLower() == ".jpeg" || strFile.Extension.ToLower() == ".gif" || strFile.Extension.ToLower() == ".bmp")
                    {
                        using (Image img = Image.FromFile(strFile.FullName))
                        {
                            sb.Append("<li>");
                            sb.Append("<a href=\"" + dir + strFile.Name + "\" title=\"" + strFile.Name + "\" class=\"image\">");
                            sb.Append("<span class=\"begin\"></span>");
                            sb.Append("<span class=\"filename\">" + strFile.Name + "</span>");
                            sb.Append("<span class=\"filetype\">" + StaticData.MIMETypesDictionary[strFile.Extension.ToLower()] + "</span>");
                            sb.Append("<span class=\"filedim\">" + img.Width + " x " + img.Height + "</span>");
                            sb.Append("<span class=\"icon image\"><img src=\"/Resources.ashx?module=popup&action=view_thumb&h=48&w=48&src=" + HttpUtility.UrlEncode(dir + strFile.Name) + "&far=1&bg=0000FF\" /></span>");
                            sb.Append("</a>");
                            sb.Append("</li>\n");
                            img.Dispose();
                        }
                    }
                    else
                    {
                        sb.Append("<li>");
                        sb.Append("<a href=\"" + dir + strFile.Name + "\" title=\"" + strFile.Name + "\" class=\"file\">");
                        sb.Append("<span class=\"begin\"></span>");
                        sb.Append("<span class=\"filename\">" + strFile.Name + "</span>");
                        sb.Append("<span class=\"filetype\">" + StaticData.MIMETypesDictionary[strFile.Extension.ToLower()] + "</span>");
                        sb.Append("<span class=\"filesize\">" + fileSize + "</span>");
                        sb.Append("<span class=\"icon " + strFile.Extension.Trim('.') + "\"></span>");
                        sb.Append("</a>");
                        sb.Append("</li>\n");
                    }
                }
            }
            sb.Append("</ul>\n");
            return sb.ToString();
        }

        private static object SynThread = new object();
        public static string do_upload(HttpFileCollection files, string uploadPath)
        {
            HttpContext context = HttpContext.Current;
            StringBuilder sb = new StringBuilder();
            try
            {
                if (files.Count > 0)
                {
                    for (int i = 0; i < files.Count; i++)
                    {
                        HttpPostedFile hpf = files[i];
                        float fileSize = 0;
                        var cType = hpf.ContentType.ToLower();
                        var extenfile = Path.GetExtension(hpf.FileName).ToLower();

                        if (hpf.ContentLength <= 0)
                        {
                            sb.Append("-1");
                            return sb.ToString();
                        }
                        fileSize = hpf.ContentLength;
                        if (fileSize > 213314770)
                        {
                            sb.Append("-3");
                            return sb.ToString();
                        }
                        string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + extenfile;
                        string pathsave = uploadPath + fileName;
                        pathsave = context.Server.MapPath(pathsave.Replace(" ", "_"));
                        lock (SynThread)
                        {
                            hpf.SaveAs(pathsave);
                        }
                        sb.Append(fileName);
                    }
                }
                else
                    sb.Append("No file choice");
            }
            catch (Exception ex)
            {
                sb.Append(ex.Message);
            }
            return sb.ToString();
        }

        public static string do_cut_paste(string[] files, string folder)
        {
            HttpContext context = HttpContext.Current;
            StringBuilder sb = new StringBuilder();
            foreach (string file in files)
            {
                string sFile = context.Server.MapPath(HttpUtility.UrlDecode(file));
                string fileName = Path.GetFileName(sFile);
                if (File.Exists(sFile))
                {
                    File.Move(sFile, context.Server.MapPath(HttpUtility.UrlDecode(folder)) + fileName);
                }
                else if (Directory.Exists(sFile))
                {
                    DirectoryInfo info = new DirectoryInfo(sFile);
                    MoveDirectory(sFile, context.Server.MapPath(HttpUtility.UrlDecode(folder)) + "\\" + info.Name);
                }
            }
            sb.Append("success||Thao tác thành công!");
            return sb.ToString();
        }
        public static string do_copy_paste(string[] files, string folder)
        {
            HttpContext context = HttpContext.Current;
            StringBuilder sb = new StringBuilder();
            foreach (string file in files)
            {
                string sFile = context.Server.MapPath(HttpUtility.UrlDecode(file));
                string fileName = Path.GetFileName(sFile);
                string desFile = context.Server.MapPath(HttpUtility.UrlDecode(folder)) + fileName;
                if (File.Exists(sFile))
                {
                    if (File.Exists(desFile))
                        File.Delete(desFile);
                    File.Copy(sFile, desFile);
                }
                else if (Directory.Exists(sFile))
                {
                    DirectoryInfo info = new DirectoryInfo(sFile);
                    desFile = desFile + "\\" + info.Name;
                    CopyDirectory(sFile, desFile);
                }
            }
            sb.Append("success||Thao tác thành công!");
            return sb.ToString();
        }
        public static string do_rename(string type, string oldname, string newname, string folder)
        {
            HttpContext context = HttpContext.Current;
            StringBuilder sb = new StringBuilder();
            switch (type)
            {
                case "file":
                    if (File.Exists(oldname))
                        File.Move(oldname, context.Server.MapPath(folder + newname));
                    break;
                case "folder":
                    if (Directory.Exists(oldname))
                        Directory.Move(oldname, context.Server.MapPath(folder + newname));
                    break;
                default:
                    if (File.Exists(oldname))
                        File.Move(oldname, context.Server.MapPath(folder + newname));
                    break;
            }
            sb.Append("success||Thao tác thành công!");
            return sb.ToString();
        }
        public static string do_delete(string[] files)
        {
            HttpContext context = HttpContext.Current;
            StringBuilder sb = new StringBuilder();
            int index = 0;
            string type = string.Empty;
            foreach (string file in files)
            {
                string sFile = HttpUtility.UrlDecode(file);
                sFile = context.Server.MapPath(sFile);
                if (File.Exists(sFile))
                {
                    File.Delete(sFile);
                    index++;
                    type = "file(s)";
                }
                else if (Directory.Exists(sFile))
                {
                    Directory.Delete(sFile, true);
                    index++;
                    type = "directory(s)";
                }
            }
            if (index > 0)
                sb.Append("success||Xóa thành công " + index + " " + type);
            else
                sb.Append("error||Không có file hoặc thư mục được chọn");
            return sb.ToString();
        }
        public static string do_create_folder(string folderName, string folderPath)
        {
            HttpContext context = HttpContext.Current;
            StringBuilder sb = new StringBuilder();
            string serverPath = context.Server.MapPath(folderPath + folderName);
            if (Directory.Exists(serverPath))
                sb.Append("error||Thư mục đã tồn tại !");
            else
            {
                Directory.CreateDirectory(serverPath);
                sb.Append("success||Thư mục đã được tạo!");
            }
            return sb.ToString();
        }

        private static void CopyDirectory(string source, string target)
        {
            var stack = new Stack<Folders>();
            stack.Push(new Folders(source, target));

            while (stack.Count > 0)
            {
                var folders = stack.Pop();
                Directory.CreateDirectory(folders.Target);
                foreach (var file in Directory.GetFiles(folders.Source, "*.*"))
                {
                    string targetFile = Path.Combine(folders.Target, Path.GetFileName(file));
                    if (File.Exists(targetFile)) File.Delete(targetFile);
                    File.Copy(file, targetFile);
                }

                foreach (var folder in Directory.GetDirectories(folders.Source))
                {
                    stack.Push(new Folders(folder, Path.Combine(folders.Target, Path.GetFileName(folder))));
                }
            }
        }

        private static void MoveDirectory(string source, string target)
        {
            var stack = new Stack<Folders>();
            stack.Push(new Folders(source, target));

            while (stack.Count > 0)
            {
                var folders = stack.Pop();
                Directory.CreateDirectory(folders.Target);
                foreach (var file in Directory.GetFiles(folders.Source, "*.*"))
                {
                    string targetFile = Path.Combine(folders.Target, Path.GetFileName(file));
                    if (File.Exists(targetFile)) File.Delete(targetFile);
                    File.Move(file, targetFile);
                }

                foreach (var folder in Directory.GetDirectories(folders.Source))
                {
                    stack.Push(new Folders(folder, Path.Combine(folders.Target, Path.GetFileName(folder))));
                }
            }
            Directory.Delete(source, true);
        }
        public class Folders
        {
            public string Source { get; private set; }
            public string Target { get; private set; }

            public Folders(string source, string target)
            {
                Source = source;
                Target = target;
            }
        }
    }
}
